#include "pid.h"



/** structure for PID parameters ********************************/


void PI_Ctrl(stc_pi_t *pstc, stc_pid_para_t *stcPIParam,int grill_temperature,int temp_set)
{
	pstc->i32Q15_Fbk = grill_temperature;
	pstc->i32Q15_Ref = temp_set;
	
	if(pstc->u8En==0)
	{
		//pstc->i32Q27_Iout=0;
		//pstc->i32Q27_Output=0;
		pstc->u8IntegralLmtFlg=0;
	}
	else
	{
		/* Error term */
		pstc->i32Q15_Err = pstc->i32Q15_Ref - pstc->i32Q15_Fbk;
		/* Intergral term */
		if(pstc->u8IntegralLmtFlg==0)
			 pstc->i32Q27_Iout += (stcPIParam->i32Q12_Ki * pstc->i32Q15_Err);
		/* control output */
		int i32Q15_Derivative = pstc->i32Q15_Err - pstc->i32Q15_LastErr;
		pstc->i32Q27_Output = pstc->i32Q27_Iout + (stcPIParam->i32Q12_Kp * pstc->i32Q15_Err)+(stcPIParam->i32Q12_Kd * i32Q15_Derivative);
		if(pstc->i32Q27_Output > stcPIParam->i32Q27_OutMax)
		{
			pstc->i32Q27_Output = stcPIParam->i32Q27_OutMax;
			pstc->u8IntegralLmtFlg=1;
		}
		else if(pstc->i32Q27_Output < stcPIParam->i32Q27_OutMin)
		{
			pstc->i32Q27_Output = stcPIParam->i32Q27_OutMin;
			pstc->u8IntegralLmtFlg=2;
		}
		else
		{
			pstc->u8IntegralLmtFlg=0;
		}
		if(pstc->i32Q27_Iout > stcPIParam->i32Q27_OutMax) pstc ->i32Q27_Iout = stcPIParam->i32Q27_OutMax;
		if(pstc->i32Q27_Iout < stcPIParam->i32Q27_OutMin) pstc->i32Q27_Iout = stcPIParam->i32Q27_OutMin;
		pstc->i32Q15_LastErr = pstc->i32Q15_Err; // Update last error for next iteration
	}
}
